﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Aga.Psad.Backend.Repositories;
using Aga.Psad.Mvc.Models.Visualizador;
using PagedList;
using MvcMembership;
using System.Web.Mvc;
using Aga.Psad.Backend.Entities;
using System.IO;
using Aga.Psad.Mvc.Models;
using System.Web.Security;

namespace Aga.Psad.Mvc.Controllers
{
    public abstract class GuardaDocumentalController : ControllerBase
    {
        protected AspNetMembershipProviderWrapper usersService;
        protected AspNetRoleProviderWrapper rolesService;

        public abstract string ControllerName { get; }

        public const int PageSize = 10;

        public GuardaDocumentalController()
        {
            usersService = new MvcMembership.AspNetMembershipProviderWrapper(Membership.Provider);
            rolesService = new MvcMembership.AspNetRoleProviderWrapper(Roles.Provider);
        }

        /// <summary>
        /// Gets the name of the user.
        /// </summary>
        /// <value>The name of the user.</value>
        protected string UserName
        {
            get
            {
                if (Request.IsAuthenticated)
                    return Request.Params["AUTH_USER"];
                else
                    return string.Empty;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is external user.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is external user; otherwise, <c>false</c>.
        /// </value>
        protected bool IsExternalUser
        {
            get
            {
                return (rolesService.IsInRole(usersService.Get(UserName), "Declarante") ||
                        rolesService.IsInRole(usersService.Get(UserName), "ImportadorExportador"));
            }
        }

        protected void BuscarDespachos(int? index, FiltroBusquedaViewModel model)
        {
            DespachoRepository despachos = new DespachoRepository();
            ClienteRepository declarantes = new ClienteRepository();
            ClienteDeClienteRepository importadores = new ClienteDeClienteRepository();

            var results = despachos.Search(UserName, model.Legajo, model.Declarante, model.ImportadorExportador, index ?? 0, PageSize);

            if (results.Count > 0)
            {
                model.MostrarResultados = true;

                var resultSet = results.Select(result => new ResultadoBusquedaViewModel
                {
                    DespachoId = result.Id,
                    Legajo = result.Legajo,
                    Declarante = result.Declarante.RazonSocial,
                    ImportadorExportador = result.ImportadorExportador.RazonSocial,
                    Caja = result.Caja
                }).AsEnumerable();

                model.Resultados = new PagedList<ResultadoBusquedaViewModel>(resultSet, index ?? 0, PageSize);
            }
        }

        protected FiltroBusquedaViewModel BuscarDespachos(string e, string d, string i, int? index)
        {
            FiltroBusquedaViewModel model = new FiltroBusquedaViewModel(false);

            if (index != null)
            {
                model.Legajo = !String.IsNullOrEmpty(e) ? e : string.Empty;
                model.Declarante = !String.IsNullOrEmpty(d) ? d : string.Empty;
                model.ImportadorExportador = !String.IsNullOrEmpty(i) ? i : string.Empty;

                if (index != -1)
                    BuscarDespachos(index, model);
            }

            return model;
        }

        [Authorize]
        public ActionResult VerDocumento(int id)
        {
            try
            {
                // ToDo: validar si el usuario logueado puede acceder al documento
                DespachoRepository despachos = new DespachoRepository();
                Despacho despacho = despachos.GetById(id);

                AuditoriaRepository audit = new AuditoriaRepository();
                audit.Auditar(UserName, AccionAuditoria.SolicitudPdf, String.Format("ID:{0}|EXPEDIENTE:{1}", despacho.Id, despacho.Legajo));

                FileStream stream = despacho.GetPdf();

                return File(stream, "application/pdf");
            }
            catch (Exception ex)
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = "No se encontró la imágen solicitada.",
                    Details = "Por favor, contacte al administrador del sistema.",
                    ControllerName = this.ControllerName
                };


                return ShowDetailedError(model);
            }
        }

    }
}
